package com.starsray.dynamic.ds.flyway;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import lombok.extern.slf4j.Slf4j;
import org.flywaydb.core.Flyway;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

@Slf4j
public class FlywayLoad {

    @Resource
    private DataSource dataSource;

    public void initFlyway() {
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        Map<String, DataSource> dataSources = ds.getDataSources();
        dataSources.forEach((poolName, value) -> {
            try {
                Connection connection = value.getConnection();
                if (connection != null) {
                    Flyway flyway = Flyway.configure().dataSource(value).load();
                    flyway.migrate();

                    log.info("flyway migrate db {} success!", poolName);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        });
    }
}